/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
/**
 * @description GiteeController.java
 * @author dongbin
 * @version 
 * @copyright
 */

package com.global.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.redragon.commons.code.MD5Util;
import org.redragon.framework.hibernate.data.SnowFlake;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.util.JsonDataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;
import org.springframework.web.servlet.view.RedirectView;

import com.erp.hr.dao.model.HrStaff;
import com.erp.hr.dao.model.HrStaffDepartmentR;
import com.erp.hr.service.HrStaffDepartmentRService;
import com.erp.hr.service.HrStaffService;
import com.erp.permission.dao.model.SysUser;
import com.erp.permission.dao.model.SysUserCO;
import com.erp.permission.dao.model.SysUserRoleR;
import com.erp.permission.service.SysUserRoleRService;
import com.erp.permission.service.SysUserService;
import com.global.util.GiteeUtil;
import com.wf.captcha.utils.CaptchaUtil;

/**
 * @description
 * @date 2020年11月5日
 * @author dongbin
 * 
 */
@Controller
@RequestMapping("/gitee")
public class GiteeController {
    
    //服务类
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleRService sysUserRoleRService;
    @Autowired
    private HrStaffService hrStaffService;
    @Autowired
    private HrStaffDepartmentRService hrStaffDepartmentRService;
    
    @RequestMapping("captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.out(request, response);
    }
    
    @RequestMapping("getRedragonErpAccount")
    @ResponseBody
    public String getRedragonErpAccount(String username, String captcha, HttpServletRequest request) {
        if(StringUtils.isNotBlank(captcha)&&StringUtils.isNotBlank(username)) {
            //判断验证码
            if (!CaptchaUtil.ver(captcha, request)) {
                CaptchaUtil.clear(request);
                return JsonDataUtil.getExecuteJson(-1, "验证码输入错误");
            }else {
                //如果username是地址则做个格式化
                if(username.contains("http:")||username.contains("HTTP:")||username.contains("https:")||username.contains("HTTPS:")) {
                    if(username.substring(username.length()-1).equals("/")) {
                        username = username.substring(0, username.length()-1);
                    }
                    
                    username = username.substring(username.lastIndexOf("/")+1);
                }
                
                boolean starFlag = GiteeUtil.isClickStar(username);
                if(!starFlag) {
                    return JsonDataUtil.getExecuteJson(-1, "请访问<a href='https://gitee.com/redragon/redragon-erp' target='_blank' class='text-warning'>【赤龙ERP】</a>，点击<b><i class='fa fa-star'></i>星标</b>后重新申请测试账号，感谢支持！");
                }else {
                    String password = SnowFlake.getConcurrentId().toString().substring(3, 12);
                    
                    //查找用户是否存在
                    Pages pages = new Pages();
                    pages.setPage(1);
                    SysUserCO sysUserCO = new SysUserCO();
                    sysUserCO.setUsername(username);
                    List<SysUser> list = this.sysUserService.getDataObjects(pages, sysUserCO);
                    
                    if(list!=null&&list.size()>0) {
                        return JsonDataUtil.getExecuteJson(-1, "您已申请过账号，请查询<a href='https://gitee.com/' target='_blank' style='color:black'><b>码云私信</b></a>！");
                    }else {
                        //创建用户
                        SysUser sysUser = new SysUser();
                        sysUser.setUsername(username);
                        sysUser.setPassword(MD5Util.encodeSHA(password));
                        sysUser.setStatus("Y");
                        sysUser.setCreatedBy("redragon");
                        this.sysUserService.insertDataObject(sysUser);
                        //用户关联角色
                        SysUserRoleR sysUserRoleR = new SysUserRoleR();
                        sysUserRoleR.setUsername(username);
                        sysUserRoleR.setRoleCode("admin_role");
                        sysUserRoleR.setCreatedBy("redragon");
                        this.sysUserRoleRService.insertDataObject(sysUserRoleR);
                        
                        sysUserRoleR = new SysUserRoleR();
                        sysUserRoleR.setUsername(username);
                        sysUserRoleR.setRoleCode("data_auth_role");
                        sysUserRoleR.setCreatedBy("redragon");
                        this.sysUserRoleRService.insertDataObject(sysUserRoleR);
                        
                        //创建职员
                        HrStaff hrStaff = new HrStaff();
                        String code = SnowFlake.getConcurrentId().toString();
                        hrStaff.setStaffCode(code);
                        hrStaff.setStaffName(username);
                        hrStaff.setStaffNumber(code);
                        hrStaff.setStaffStatus("WORK");
                        hrStaff.setUsername(username);
                        hrStaff.setCreatedBy("redragon");
                        this.hrStaffService.insertDataObject(hrStaff);
                        
                        //创建职员部门关联
                        HrStaffDepartmentR hrStaffDepartmentR = new HrStaffDepartmentR();
                        hrStaffDepartmentR.setDepartmentCode("java");
                        hrStaffDepartmentR.setPositionCode("java");
                        hrStaffDepartmentR.setStaffCode(code);
                        hrStaffDepartmentR.setStatus("Y");
                        hrStaffDepartmentR.setCreatedBy("redragon");
                        this.hrStaffDepartmentRService.insertDataObject(hrStaffDepartmentR);
                    }
                    
                    boolean sendFlag = GiteeUtil.sendErpAccount(username, "感谢您对【赤龙ERP】的青睐；账号："+username+"，密码："+password);
                    if(!sendFlag) {
                        return JsonDataUtil.getExecuteJson(-1, "程序报错了，请稍后再试或直接联系<a href='https://gitee.com/redragon/redragon-erp' target='_blank' class='text-warning'><b>【赤龙ERP】</b></a>的开发者");
                    }else {
                        return JsonDataUtil.getExecuteJson(-1, "【赤龙ERP】的账号和密码已发送私信到您码云的账号，请登陆<a href='https://gitee.com/' target='_blank' style='color:black'><b>码云</b></a>查看！");
                    }
                }
            }
        }
        
        return JsonDataUtil.getExecuteJson(-1, "程序报错了，账号和密码未创建成功！请稍后再试或直接联系<a href='https://gitee.com/redragon/redragon-erp' target='_blank' class='text-warning'>【赤龙ERP】</a>的开发者");
    }
    
    @RequestMapping("loginAuth")
    public ModelAndView loginAuth(HttpServletRequest request, HttpServletResponse response) {
        //获取用户授权码
        String authCode = request.getParameter("code");
        //获取token
        String token = GiteeUtil.getTokenByAuth(authCode, response);
        //获取login
        String login = GiteeUtil.getLoginNameByAuth(token);
        
        RedirectView redirectView = new RedirectView("http://www.redragon-erp.com/account.html?username="+login, false);
        return new ModelAndView(redirectView);
    }
    
}
